package com.csc531.lists;

import java.util.ArrayList;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.csc531.R;
import com.csc531.DataTypes.Note;
import com.csc531.adapters.NotesDbAdapter;
import com.csc531.adapters.NotesListAdapter;
import com.csc531.edit.NotesEdit;

public class NotesThinList extends ThinList
{
	//logging
	private static final String TAG = "NOTES TAB";
	
	//activity results
	private static final int ACTIVITY_CREATE=0;
	private static final int ACTIVITY_EDIT=1;

	//menu
	private static final int INSERT_ID = Menu.FIRST;
	private static final int EDIT_ID = Menu.FIRST + 1;
	private static final int DELETE_ID = Menu.FIRST + 2;

	//globals
	private ArrayList<Integer> _notesDatabaseRowIds;
	private NotesDbAdapter _mDbHelper;
	

	//---------------------------------------------------------------------------------
	

	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) 
	{
        super.onActivityResult(requestCode, resultCode, intent);
        fillNoteListData();
        
    }
	
	/* (non-Javadoc)
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView, android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id)
	{
		
		((NotesListAdapter)getListAdapter()).toggle(position);

	}

	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		super.onCreateOptionsMenu(menu);
		menu.add(0, INSERT_ID, 0, R.string.notemenu_insert);
		menu.add(0, EDIT_ID, 0, R.string.notemenu_edit);
		menu.add(0, DELETE_ID, 0,  R.string.notemenu_delete);
		
		return true;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onMenuItemSelected(int, android.view.MenuItem)
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) 
	{
		switch(item.getItemId()) 
		{
		case INSERT_ID:
			createNote();
			return true;
		case EDIT_ID:
			editNote();
			return true;
		case DELETE_ID:
			deleteNote();
			fillNoteListData();
			return true;
		}

		return super.onMenuItemSelected(featureId, item);
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		_mDbHelper = new NotesDbAdapter(this);
		_mDbHelper.open();
		fillNoteListData();
	}

	/**
	 * Fill the tab with a list object containing the tasks
	 */
	public void fillNoteListData() 
	{

		NotesListAdapter notesTabAdapter = new NotesListAdapter(this);
		_notesDatabaseRowIds = new ArrayList<Integer>();
		
		
		Cursor noteCursor = _mDbHelper.fetchAllNotes();
		startManagingCursor(noteCursor);
		
        String[] from = new String[]{NotesDbAdapter.KEY_TITLE};
        int[] to = new int[]{R.id.text1};
        
        SimpleCursorAdapter simpleNoteCursor = 
        	    new SimpleCursorAdapter(this, R.layout.notes_row, noteCursor, from, to);
       
        printNotesToClassesTab(simpleNoteCursor,notesTabAdapter);

		//setListAdapter here
		notesTabAdapter.createGlobalTaskList();
		setListAdapter(notesTabAdapter);
	}
	
	/**
	 * Queries the SQLlite to populate the contents of the tab
	 * @param simpleNoteCursor
	 * @param notesTabAdapter
	 */
	private void printNotesToClassesTab(SimpleCursorAdapter simpleNoteCursor, NotesListAdapter notesTabAdapter) 
	{
		 try
		 {
	        	simpleNoteCursor.getCursor().moveToFirst();
	            
	    		int numberOfRows = simpleNoteCursor.getCursor().getCount();
	    		int numberOfColumns = simpleNoteCursor.getCursor().getColumnCount();

	    		Log.v(TAG, "num of rows: "+numberOfRows);
	    		Log.v(TAG, "num of cols: "+numberOfColumns);
	    		
	    		for( int i = 0; i < numberOfRows ; i++ ) 
	    		{
	    			addNotesToCourse(simpleNoteCursor,notesTabAdapter);
	    			
	    			simpleNoteCursor.getCursor().moveToNext();
	    		}
	       
		 } 
		 catch(RuntimeException ex) 
		 {
	        	Log.v(TAG,"The List is Empty!!");
	        
		 }
	}
	
	/**
	 * Traverses the database table and creates Course objects and appends Tasks objects to them
	 * @param simpleNoteCursor
	 * @param notesTabAdapter
	 */
	private void addNotesToCourse(SimpleCursorAdapter simpleNoteCursor, NotesListAdapter notesTabAdapter) 
	{
		int k = 0;
		
		String rowId = simpleNoteCursor.getCursor().getString(k++);
		_notesDatabaseRowIds.add(Integer.parseInt(rowId));
		
		Note note = new Note();
		
		String title = simpleNoteCursor.getCursor().getString(k++);
		
		Log.v(TAG,"note title: "+title);
		note.setTitle(title);
		
		String body = simpleNoteCursor.getCursor().getString(k++);
		note.setBody(body);
		Log.v(TAG,"note body: "+body);

		notesTabAdapter.addNote(note);
	}
	

	/**
	 * Action method that creates a new Note
	 */
	private void createNote() 
	{
		Intent i = new Intent(this, NotesEdit.class);
		startActivityForResult(i, ACTIVITY_CREATE);
	}
	
	/**
	 * Action method to edit a selected Note
	 */
	private void editNote() 
	{
		Intent i = new Intent(this, NotesEdit.class);
		
		if(checkNotesExist() == false) 
		{
			return;
		}
		
		long id = _notesDatabaseRowIds.get((int) getSelectedItemId());
		
		Log.v(TAG, "The id from onlistitemclick is: "+id);

		i.putExtra(NotesDbAdapter.KEY_ROWID,id);
		startActivityForResult(i, ACTIVITY_EDIT);
	}
	
	/**
	 * Action method to delete a selected Note
	 */
	private void deleteNote() 
	{
		if(checkNotesExist() == false)
		{
			return;
		}
		
		_mDbHelper.deleteNote(_notesDatabaseRowIds.get((int) getListView().getSelectedItemId()));
	}
	
	/**
	 * Helper method to prevent OutOfBoundsException in the
	 * _notesDatabaseRowIds ArrayList
	 * 
	 * @return false if the ArrayList is empty
	 */
	private boolean checkNotesExist() 
	{
		if(_notesDatabaseRowIds.size() <= 0)
		{
			return false;
		}
		else 
		{
			return true;
		}
	}
}
